﻿using MapleLeaf.Pay.Pay;
using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Navigation;

namespace MapleLeaf.Client {
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>W
    public partial class MainWindow : Window, IComponentConnector {

        private Button _SelectTabButton;
        private static readonly int HKShowHideId;
        static MainWindow() {
            HKShowHideId = 39321;
        }


        public MainWindow() : base() {

            HongshPayApi.GateWay = new Uri(App.Descript);
            string[] files = Directory.GetFiles("./", "MapleLeaf.Client.*.dll");
            foreach (string path in files) {
                Assembly assembly = Assembly.UnsafeLoadFrom(Path.GetFullPath(path));
                Type[] types = assembly.GetTypes();
                foreach (Type type in types) {
                    if (!type.IsAbstract && typeof(HongshPayClientPlugin).IsAssignableFrom(type)) {
                        try {
                            HongshPayClientContext.Default.Plugins.Add((HongshPayClientPlugin)Activator.CreateInstance(type, new object[]
                            {
                                HongshPayClientContext.Default
                            }));
                        }
                        catch (Exception e) {
                            App.ProcessException(e);
                        }
                        break;
                    }
                }
            }
            Title = App.Title;
            DataContext = HongshPayClientContext.Default;
            _ = new FloatWindow();
        }


        public Button SelectTabButton {
            get => _SelectTabButton;
            set {
                if (value != _SelectTabButton) {
                    if (_SelectTabButton != null) {
                        _SelectTabButton.Style = FindResource("STYLETableButtonFloat") as Style;
                    }
                    _SelectTabButton = value;
                    if (_SelectTabButton == null) {
                        TableContent.Content = null;
                    }
                    else {
                        _SelectTabButton.Style = FindResource("STYLETableButtonFloatPressed") as Style;
                        _ = TableContent.Navigate(value.CommandParameter);
                    }
                }
            }
        }


        protected override void OnInitialized(EventArgs e) {
            base.OnInitialized(e);
            Loaded += MainWindow_Loaded;
        }


        private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
            (PresentationSource.FromVisual(this) as HwndSource).AddHook(new HwndSourceHook(WndProc));
            HongshPayClientContext.Default.Config.PropertyChanged += HongshPayClientConfig_PropertyChanged;
            if (HongshPayClientContext.Default.Config.HideOnLoad) {
                Hide();
            }
            ResetHotkey();
            SelectTabButton = CashPageTabButton;
        }


        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {
            try {
                if (wParam.ToInt32() == HKShowHideId) {
                    if (Keyboard.IsKeyDown(Key.End)) {
                        Shutdown(null, null);
                    }
                    else {
                        SwithVisible(null, null);
                    }
                }
            }
            catch {

            }
            return IntPtr.Zero;
        }


        private void HongshPayClientConfig_PropertyChanged(object sender, PropertyChangedEventArgs e) {
            if (e.PropertyName == "HKShowHide") {
                ResetHotkey();
            }
        }

        /// <summary>
        /// 注册热键
        /// </summary>
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, int vk);

        /// <summary>
        /// 注销热键
        /// </summary>
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        /// <summary>
        /// 重置
        /// </summary>
        private void ResetHotkey() {
            if (!string.IsNullOrEmpty(HongshPayClientContext.Default.Config.HKShowHide)) {
                IntPtr handle = new WindowInteropHelper(this).Handle;
                int vk = KeyInterop.VirtualKeyFromKey((Key)new KeyConverter().ConvertFromString(HongshPayClientContext.Default.Config.HKShowHide));
                _ = UnregisterHotKey(handle, HKShowHideId);
                if (!RegisterHotKey(handle, HKShowHideId, 0U, vk)) {
                    throw new Exception(string.Format("快捷键注册失败，[{0}] 已被占用！", HongshPayClientContext.Default.Config.HKShowHide));
                }
            }
        }


        private void Shutdown(object sender, EventArgs e) {
            if (MessageBox.Show("退出后将影响您的线上支付功能，若您不了解该操作带来的影响请选择取消，请确认是否继续退出？", App.Title, MessageBoxButton.OKCancel, MessageBoxImage.Exclamation, MessageBoxResult.Cancel, MessageBoxOptions.ServiceNotification) == MessageBoxResult.OK) {
                Environment.Exit(0);
            }
        }


        public void SwithVisible(object sender, EventArgs e) {
            if (IsVisible) {
                Hide();
            }
            else {
                Show();
                WindowState = WindowState.Normal;
            }
        }


        private void Table_Click(object sender, RoutedEventArgs e) {
            SelectTabButton = sender as Button;
        }


        private void TableContent_Navigating(object sender, NavigatingCancelEventArgs e) {
            if (e.NavigationMode == NavigationMode.Back) {
                e.Cancel = true;
            }
            if (e.Content is FrameworkElement && (e.Content as FrameworkElement).DataContext == null) {
                (e.Content as FrameworkElement).DataContext = DataContext;
            }
        }


        private void Grid_MouseMove(object sender, MouseEventArgs e) {
            if (e.LeftButton == MouseButtonState.Pressed) {
                DragMove();
            }
        }


        protected override void OnStateChanged(EventArgs e) {
            if (WindowState == WindowState.Minimized) {
                Hide();
            }
            base.OnStateChanged(e);
        }

        protected override void OnClosing(CancelEventArgs e) {
            WindowState = WindowState.Minimized;
            e.Cancel = true;
            base.OnClosing(e);
        }

        private void Close_Click(object sender, RoutedEventArgs e) {
            Close();
        }


    }
}
